package com.ifonly.ar.sql.mapper;

import com.ifonly.ar.core.Config;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import java.io.File;
import java.io.FileFilter;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ifonly
 * @version 1.0 2015-12-07 15:34
 * @since JDK 1.6
 */
public class SqlMapper {

    private static Map<String, String> sqlMapping = new HashMap<String, String>();

    public static void init() {
        final URL resource = SqlMapper.class.getClassLoader().getResource(Config.SQL_MAPPER);
        if (resource == null) {
            throw new NullPointerException("the resources is null.");
        }

        List<File> files = mapperFiles(new File(resource.getFile()));

        initSqlMapping(files);
    }

    private static void initSqlMapping(List<File> files) {
        try {
            JAXBContext cxt = JAXBContext.newInstance(Sqls.class);
            Unmarshaller unmarshaller = cxt.createUnmarshaller();

            for (File file : files) {
                Sqls sqls = (Sqls) unmarshaller.unmarshal(file);
                String sqlsId = sqls.id;
                List<Sql> sql = sqls.sql;
                for (Sql s : sql) {
                    String sqlId = s.id;
                    String value = s.value.trim();
                    String key = sqlsId + "." + sqlId;
                    if (sqlMapping.get(key) != null) {
                        throw new RuntimeException("The Key[" + key + "] exist");
                    }

                    sqlMapping.put(key, value);
                }
            }
        } catch (JAXBException e) {
            e.printStackTrace();
            throw new RuntimeException("Parse mapper file [" + files + "] failed", e);
        }
    }

    static List<File> mapperFiles(final File file) {
        List<File> list = new ArrayList<File>();

        File[] files = file.listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.isDirectory() || pathname.getName().endsWith(Config.MAPPER_SUFFIX);
            }
        });

        for (File f : files) {
            if (f.isDirectory()) {
                list.addAll(mapperFiles(f));
            } else {
                list.add(f);
            }
        }
        return list;
    }

    private static String getSql(String key) {
        return sqlMapping.get(key);
    }

}
